package com.cn.dao;

import java.util.List;

import javax.enterprise.inject.New;
import javax.management.Query;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;







import com.cn.domain.Customer;

public class CustomerDao extends HibernateDaoSupport{

	/*
	 * 检测该用户是否存在
	 */
	public Customer getLoginUsername(String loginusername) {
	String hqlString = "from Customer where loginUsername=?";
	List<Customer> customers = this.getHibernateTemplate().find(hqlString, loginusername);
	if(customers.size()>0){
    Customer c =customers.get(0);
	return c;
	}
    return null;
	}

	public void addCustomer(Customer customer) {
	
		this.getHibernateTemplate().save(customer);
		
	}

	public Customer getLoginCustomer(String loginUsername, String password) {
		String hql=" from Customer where loginUsername=? and password=? and role=1 ";
	   // List<Customer> custlist =this.getHibernateTemplate().find(hql,new Object[]{loginUsername,password});
		 SessionFactory sf = this.getSessionFactory();
	      Session session =  sf.openSession();
		 List<Customer> custlist =  session.createQuery(hql)
				                     .setString(0, loginUsername)
				                      .setString(1, password).list();
		System.out.println("size"+custlist.size());
	    if(custlist.size()>0){
	    	System.out.println("password"+custlist.get(0).getPassword());
		return custlist.get(0);
	}else{
	return null;
	}
	}

	public void updatemessage(Customer customer) {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().update(customer);
	}

	public Customer getLoginAdmin(String loginUsername, String password) {
		String hql=" from Customer where loginUsername=? and password=? and role=2 ";
		 SessionFactory sf = this.getSessionFactory();
	      Session session =  sf.openSession();
		 List<Customer> custlist =  session.createQuery(hql)
				                     .setString(0, loginUsername)
				                      .setString(1, password).list();
		System.out.println("size"+custlist.size());
	    if(custlist.size()>0){
	    	System.out.println("password"+custlist.get(0).getPassword());
		return custlist.get(0);
	}else{
	return null;
	}
		 
	
	}

	public List<Customer> findAllCustomer() {
	
		String hqlString="from Customer where role=1";
	List<Customer> cList = this.getHibernateTemplate().find(hqlString);
	if(cList.size()>0){
		return cList;
	}
	return null;
	}

	public void deleteCustomer(int cid) {
		Customer customer =(Customer) this.getHibernateTemplate().get(Customer.class, cid);
	    this.getHibernateTemplate().delete(customer);	
	}

	public Customer getExitLoginUsername(String loginUsername) {
		String hqlString="from Customer where loginUsername=?";
		List<Customer> customers = this.getHibernateTemplate().find(hqlString, loginUsername);
		if(customers.size()>0){
	    Customer c =customers.get(0);
		return c;
		}
	    return null;
		}

	
	}







